const Service = require('egg').Service;

class CommonService extends Service {
	
	// 添加请求日志
	async addReqLog(ip, reqUrl, reqData) {

		const result = await this.app.mysql.insert('pay_request_log', {
			prlIp: ip,
			prlUrl: reqUrl,
			prlData: JSON.stringify(reqData)
		});
		//{
		//fieldCount: 0,
		//affectedRows: 1,
		//insertId: 3710,
		//serverStatus: 2,
		//warningCount: 2,
		//message: '',
		//protocol41: true,
		//changedRows: 0
		//}
		return result.insertId;
	}

	// 更新请求日志结果
	async setReqLog(prlId, rtnData) {
		const row = {
			prlReturn: rtnData
		};

		const options = {
			where: {
				prlId: prlId
			}
		};
		await this.app.mysql.update('pay_request_log', row, options); // 更新 posts 表中的记录
	}
	
	// 签名
	async createTkSign(paramJson, secretStr) {

		if (paramJson.hasOwnProperty("sign")){
			delete paramJson.sign;
		}

		let arr=[];
        for(var key in paramJson){
            arr.push(key)
        }
        arr.sort();
		let str='';
        for(var i in arr){
           str += "&" + arr[i] + "=" + paramJson[arr[i]];
        }

        str = str.substr(1);
        
        var crypto = require('crypto');
        var md5 = crypto.createHash('md5');
        str += secretStr;
        console.log('checkStr:' + str);
    	return md5.update(str).digest('hex');
	}
	
	// 通知用户日志
	async addNotifyLog(pnNoticeUrl, pnOrderId, pnData) {

		const result = await this.app.mysql.insert('pay_notify', {
			pnNoticeUrl: pnNoticeUrl,
			pnOrderId: pnOrderId,
			pnData: JSON.stringify(pnData)
		});

		return result.insertId;
	}
	
	// 更新通知用户返回结果
	async setNotifyLog(pnId, pnReturn) {
		
		if (typeof(pnReturn) == "object"){
			pnReturn = JSON.stringify(pnReturn);
		}
		const row = {
			pnReturn: pnReturn
		};

		const options = {
			where: {
				pnId: pnId
			}
		};
		await this.app.mysql.update('pay_notify', row, options); // 更新 posts 表中的记录
	}
	
	// 更新商户配置
	async setCustomConfig(pcId, pcPayConfig) {
		const row = {
			pcPayConfig: JSON.stringify(pcPayConfig)
		};

		const options = {
			where: {
				pcId: pcId
			}
		};
		await this.app.mysql.update('pay_customer', row, options); // 更新 posts 表中的记录
	}
}

module.exports = CommonService;